package com.hbfec.demo.excel.importor;

import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽象类
 *
 * @param <T> excel对应的实体类型
 */
public abstract class AbstractExcelImporter<T> {

    private List<T> successList = new ArrayList<>();
    private List<ErrorRowInfo> errorList = new ArrayList<>();

    /**
     * 获取实体类型
     */
    abstract Class<T> getEntityType();


    /**
     * 处理成功时的结果
     *
     * @param successList
     */
    abstract public void handleSuccessList(List<T> successList);


    /**
     * 处理一条成功的记录，可自定义是否有特殊条件不加入或加入
     *
     * @param entity
     */
    void handleOneSuccess(T entity) {
        successList.add(entity);
    }

    public void processExcel(InputStream inputStream) {
        ExcelKit.$Import(getEntityType())
                .readXlsx(inputStream, new ExcelReadHandler<T>() {
                    @Override
                    public void onSuccess(int i, int i1, T t) {
                        handleOneSuccess(t);
                    }

                    @Override
                    public void onError(int i, int i1, List<ExcelErrorField> list) {
                        errorList.add(new ErrorRowInfo(i, i1, list));
                    }
                });
    }

    public List<T> getSuccessList() {
        return successList;
    }

    public List<ErrorRowInfo> getErrorList() {
        return errorList;
    }




    class ErrorRowInfo {
        int sheetIndex;
        int rowIndex;
        List<ExcelErrorField> errorFields;

        public ErrorRowInfo(int sheetIndex, int rowIndex,
                            List<ExcelErrorField> errorFields) {
            this.sheetIndex = sheetIndex;
            this.rowIndex = rowIndex;
            this.errorFields = errorFields;
        }

        public int getSheetIndex() {
            return sheetIndex;
        }

        public int getRowIndex() {
            return rowIndex;
        }

        public List<ExcelErrorField> getErrorFields() {
            return errorFields;
        }
    }



}
